package com.cxs.controller;

import com.cxs.utils.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Project: file-upload-demo
 * @Author: cxs2014501@163.com
 * @Create: 2023/3/8 10:07
 * @Description:
 **/
@RestController
public class FileUploadController {

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @PostMapping("/upload")
    public Map<String, Object> upload(@RequestParam("file")MultipartFile file){
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        try {
            if (!ObjectUtils.isEmpty(file)) {
                // 获取源文件的名字
                String originalFilename = file.getOriginalFilename();
                if (StringUtils.hasLength(originalFilename)) {
                    // 进行文件上传
                    String url = fileUploadUtil.uploadAndUrl(originalFilename, file.getBytes());
                    result.put("data", url);
                }
            } else {
                result.put("code", 400);
                result.put("msg", "文件不能为空!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "文件上传失败!");
        }
        return result;
    }
}
